//
//  DetailViewController.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/12.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "DetailViewController.h"

#import "LxRoundScrollView.h"

#import "DetalilPriceCell.h"

#import "ImageCell.h"

#import "ButtonCell.h"

#import "DetailTableHeaderView.h"

#include "DetailImageView.h"

#import "DetailBottomTool.h"

#import "LXMallShareView.h"

#import "ImageDetailController.h"

#import "SpecificationCell.h"

#import "LXShopCartController.h"

static  NSString *const  DetalilPriceCellID = @"DetalilPriceCell";
static  NSString *const  SpecificationCellID = @"SpecificationCell";
@interface DetailViewController ()<UITableViewDelegate,UITableViewDataSource,DetailBottomToolDelegate>{
    BOOL _navBarFLag;
}


@property(nonatomic,strong)UIBezierPath * startPath;

@property(nonatomic,strong)UIBezierPath * endPath;

@property(nonatomic,assign)BOOL isEndAnimatied;

@property(nonatomic,strong)DetailBottomTool * bottomTool;

@property(nonatomic,strong)UIView * tableHeaderView;

@property(nonatomic,strong)UIButton * pullUpbutton;

@property(nonatomic,strong)LXMallShareView * shareView;

@property(nonatomic,strong)NSArray * specArray;



@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _navBarFLag = self.navigationController.navigationBar.hidden;
    //取消右滑返回手势
    [self xw_registerBackInteractiveTransitionWithDirection:XWInteractiveTransitionGestureDirectionRight transitonBlock:^(CGPoint startPoint) {
    } edgeSpacing:20];
    
    //瀑布流详情
    DetailImageView * detailView = [[DetailImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.detailView = detailView;
    [self.view addSubview:self.detailView];
    
    [self.view addSubview:self.tableView];
    
    self.imageView.frame = CGRectMake(10, ScreenWidth/Ratio_home_banner-self.imageView.height*0.5, self.imageView.width, self.imageView.height);
    [self.tableView addSubview:self.imageView];
    self.isEndAnimatied = NO;
    
    [self.view addSubview:self.bottomTool];
    [self.view bringSubviewToFront:self.bottomTool];
    self.tableView.hidden = NO;
    self.detailView.hidden = NO;
    self.bottomTool.hidden = NO;
    
    self.isSysytemBack = YES;

    UIButton * pullUpbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImageView  * imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pull_down3"]];
    [pullUpbutton addSubview:imgv];
    self.pullUpbutton = pullUpbutton;
    //MARK:底部上拉按钮tag = -100
    pullUpbutton.tag = -100;
    pullUpbutton.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    pullUpbutton.height = 40;
    pullUpbutton.width = ScreenWidth;
    pullUpbutton.y = ScreenHeight;
    imgv.size = (CGSize){pullUpbutton.height*0.5,pullUpbutton.height*0.5};
    imgv.x = pullUpbutton.width * 0.5 - imgv.width*0.5;
    imgv.y = (pullUpbutton.height - imgv.height)*0.5;
    [pullUpbutton addTarget:self action:@selector(pullUpbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pullUpbutton];


    
    self.imageView.userInteractionEnabled = YES;
    [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClick)]];
    
    [self getSpec];
    NSLog(@"%s,导航栏%@",__func__,self.navigationController.navigationBar.hidden?@"隐藏":@"显示");
}


#pragma mark - 将要出现
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.bottomTool.count = self.product.numberInShopCart;
    [self setUpNavi];
    LCTabBarController * tbvc = (LCTabBarController*)self.tabBarController;
    tbvc.tabBarHidden = YES;
    NSLog(@"%s,导航栏%@",__func__,self.navigationController.navigationBar.hidden?@"隐藏":@"显示");
    
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    LCTabBarController * tbvc = (LCTabBarController*)self.tabBarController;
    tbvc.tabBarHidden = NO;
}

#pragma mark - 已经出现
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.delegate = self.animator;
    [self.tableView reloadData];
    [[LXDataManager manager] getProductDetailWithProduct_id:self.product.product_id complete:^(BOOL success, id res) {
        if(success){
            self.detailView.detailImageArray = [res intro_img];
        }
    }];
    [ShopCartManager getAllProductComplete:^(NSArray *datas) {
        BOOL havefound = NO;
        for (Product * p in datas) {
            if([p.product_id isEqualToString:self.product.product_id]){
                self.product = p;
                havefound = YES;
            }
        }
        if(!havefound){
            self.product.numberInShopCart = 0;
        }
        self.bottomTool.count = self.product.numberInShopCart;
    }];
    
    
    NSLog(@"%s,导航栏%@",__func__,self.navigationController.navigationBar.hidden?@"隐藏":@"显示");
    self.bottomTool.y = ScreenHeight-Ratio_Detail_Height(167)-(_navBarFLag?64:0);
}

#pragma mark - 设置导航栏
-(void)setUpNavi{
    self.navigationItem.title= @"";
    self.navigationItem.leftBarButtonItem = nil;
    UINavigationBar * navigationBar = self.navigationController.navigationBar;
       //设置导航栏透明
    navigationBar.translucent = YES;
    UIImage * backgroundImage = [UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(ScreenWidth, 64)];
    UIImage * shadowImage = [UIImage imageWithColor:[UIColor clearColor] size:CGSizeMake(ScreenWidth, 1)];
    
    [navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:shadowImage];
    navigationBar.userInteractionEnabled = YES;
    
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //MARK:导航返回按钮tag = -200
    backButton.tag = -200;
    backButton.frame = CGRectMake(0, 0, 30, 30);
    [backButton addRadius:15];
    backButton.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.3];
    [backButton setImage:[UIImage imageNamed:@"nav_return_white"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [backButton addTarget:self action:@selector(pullUpbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(0, 0, 20, 20);
    [shareButton setImage:[UIImage imageNamed:@"detail_but_share"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:shareButton];
    [shareButton addTarget:self action:@selector(shareButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 分享点击事件
-(void)shareButtonClick:(UIButton*)aButton{
    [self.shareView show];
}

#pragma mark - 图片点击事件
-(void)imageViewClick{
    NSLog(@"%s",__func__);

}



#pragma mark - 获得商品规格
-(void)getSpec{
    [[LXDataManager manager] getSpecWithProductID:self.product.product_id complete:^(BOOL success, id res) {
        if(success){
            self.specArray = res;
        }
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/**
 *  懒加载tableView
 */
-(UITableView*)tableView{
    if(_tableView == nil){
        UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
         tableView.backgroundColor = [UIColor clearColor];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.sectionFooterHeight = 0;
        tableView.sectionHeaderHeight = 0;
        tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        tableView.showsVerticalScrollIndicator = NO;
        tableView.contentInset = UIEdgeInsetsMake(self.navigationController.navigationBar.hidden?-64:0, 0, 0, 0);
        
        
        CAGradientLayer * gradientLayer = [CAGradientLayer layer];
        CGRect rect = CGRectMake(0, ScreenWidth/Ratio_home_banner, ScreenWidth, tableView.height - ScreenWidth/Ratio_home_banner);
        gradientLayer.bounds = rect;
        gradientLayer.borderWidth = 0;
        gradientLayer.frame = rect;
        NSArray * colors = [NSArray arrayWithObjects:
                            (id)HexColor(@"#EEEEEE").CGColor,
                            (id)HexColor(@"#EEEEEE").CGColor, nil];
        gradientLayer.colors = colors;
        gradientLayer.endPoint = CGPointMake(0.5, 0);
        gradientLayer.startPoint = CGPointMake(0.5, 1);
        [tableView.layer insertSublayer:gradientLayer atIndex:0];
        
        DetailTableHeaderView * view = [[DetailTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth/Ratio_home_banner)];
        view.userInteractionEnabled = YES;
        view.title = self.product.name;
        self.tableHeaderView = view;
        view.pullDownHandle = ^(DetailTableHeaderView*header){
            [self handlePullDown];
        };
        tableView.tableHeaderView = view;
        _tableView = tableView;
    }
    return _tableView;
}

-(DetailBottomTool*)bottomTool{
    if(_bottomTool == nil){
        _bottomTool = [[DetailBottomTool alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, Ratio_Detail_Height(167))];
        _bottomTool.delegate = self;
        _bottomTool.product = self.product;
        
    }
    return _bottomTool;
}

#pragma mark DetailBottomTool Delegate
-(void)DetailBottomTool:(DetailBottomTool *)tool didClickAddToShopCartButton:(UIButton *)button{
    CheckLogin
    if(LoginState){
        [ShopCartManager addProduct:self.product complete:^(NSArray *datas) {
            [tool addAnimation];
        }];
        
    }
}

-(void)DetailBottomTool:(DetailBottomTool *)tool didClickShopCartButton:(UIButton *)button{
    CheckLogin
    if(LoginState){
        self.navigationController.delegate = (id)self.navigationController;
        LXShopCartController * vc = [[LXShopCartController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - tableView相关代理
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (section==0||section==1||section==2)?1:(self.specArray?self.specArray.count:0);
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        DetalilPriceCell * cell = [[UINib nibWithNibName:@"DetailCell" bundle:nil] instantiateWithOwner:nil options:nil][0];
        cell.marginLeft = self.imageView.right;
        cell.product = self.product;
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    else if (indexPath.section == 1){
        ButtonCell * cell = [[UINib nibWithNibName:@"DetailCell" bundle:nil] instantiateWithOwner:nil options:nil][1];
        cell.cellHeight = 40;
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    else if (indexPath.section == 2){
        ImageCell * cell = [[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] instantiateWithOwner:nil options:nil][1];
        cell.cellHeight = 90;
        cell.cellImage.image = [UIImage imageNamed:@"detail_ensure."];
        cell.margin = globalMargin;
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    else{
        SpecificationCell * cell = [tableView dequeueReusableCellWithIdentifier:SpecificationCellID];
        if(!cell){
            cell = [[SpecificationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SpecificationCellID];
        }
        if(self.specArray){
            SpecModel * model = self.specArray[indexPath.row];
            [cell setTitle:model.pro_spec_name content:model.pro_spec_value];
        }
        [self addCellHeight:cell.cellHeight indexPath:indexPath];
        return cell;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self cellHeightForIndexPath:indexPath];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint contentOffset = scrollView.contentOffset;
    CGFloat ratio = contentOffset.y/ScreenHeight;
    if(ratio<-0.06){
        [UIView animateWithDuration:0.5 animations:^{
            self.tableView.y = ScreenHeight;
            self.bottomTool.y = ScreenHeight;
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                self.pullUpbutton.y = ScreenHeight-self.pullUpbutton.height;
            }];
        }];
    }
}



//MARK:下拉按钮点击
-(void)handlePullDown{
    [self _hiddenTableView];
}

//MARK:返回 或 tableView出现
-(void)pullUpbuttonClick:(UIButton*)button{
    if(button.tag == -100){
        //TODO:tableView出现动画
        [self _shouTableView];
    }
    else{
        if(self.tableView.y == ScreenHeight){
            [self _shouTableView];
        }
        else{
            //TODO:返回上一个页面
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}


-(void)_shouTableView{
    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.y = 0;
        self.detailView.detailwebView.scrollView.contentOffset = (CGPoint){0,0};
        self.pullUpbutton.y = ScreenHeight;
        self.bottomTool.y = ScreenHeight - self.bottomTool.height;
    }];
}
-(void)_hiddenTableView{
    [UIView animateWithDuration:0.5 animations:^{
        self.tableView.y = ScreenHeight;
        self.detailView.detailwebView.scrollView.contentOffset = (CGPoint){0,0};
        self.pullUpbutton.y = ScreenHeight - self.pullUpbutton.height;
        self.bottomTool.y = ScreenHeight;
    }];
}

-(void)dealloc{
    NSLog(@"%s",__func__);
}

#pragma mark - 懒加载 分享的view
-(LXMallShareView*)shareView{
    WeakSelf(ws);
    if(_shareView == nil){
       _shareView =  [[LXMallShareView alloc] initWithFrame:CGRectMake(0, ScreenSize.height, ScreenSize.width, 200)];
        _shareView.shareMethon = ^(ShareMethon methon){
            switch (methon) {
                case ShareMethonWechat:
                case ShareMethonWechatFriend:{
                    SendMessageToWXReq * sendReq = [[SendMessageToWXReq alloc] init];
                    sendReq.bText = NO;
                    sendReq.scene = methon;
                    WXMediaMessage * urlMessege = [WXMediaMessage message];
                    urlMessege.title = ws.product.name;
                    urlMessege.description = ws.product.subname;
                    [urlMessege setThumbImage:ws.imageView.image];
                    WXWebpageObject * webObj = [WXWebpageObject object];
                    webObj.webpageUrl = [NSString stringWithFormat:@"http://app.lx139.com/app/product/%@",ws.product.product_id];
                    urlMessege.mediaObject = webObj;
                    sendReq.message = urlMessege;
                    sendReq.openID = WeiXin_AppKey;
                    [WXApi sendReq:sendReq];
                }break;
                    
                default:
                    break;
            }
        };
    }
    return _shareView;
}
@end







